/*
 * Group 3, User Interface Programming II (vt11)
 * Pooya | Flora | Monica | Can
 */
package vical.model;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import vical.controller.EntryController;

/**
 * The model for the week view. contains several Day Models
 * 
 * @author Can
 */
public class WeekModel {

    private List<DayModel> dayModels;
    private int dayNumbers;   // a week
    private Calendar firstday;
    private List<Entry> entries;

    private WeekModel() {
    }

    public WeekModel(List<Entry> entries) {
        this.entries = entries;
        this.firstday = Calendar.getInstance();
        this.dayNumbers = 7;
        init();
    }

    public WeekModel(List<Entry> entries, Calendar firstDay) {
        this.entries = entries;
        this.firstday = firstDay;
        this.dayNumbers = 7;
        init();
    }

    private void init() {
        if (dayModels == null) {
            dayModels = new ArrayList<DayModel>();
        }
        Calendar day = (Calendar) firstday.clone();
        for (int i = 0; i < dayNumbers; i++) {
            dayModels.add(new DayModel(entries, day));
            day.add(Calendar.DATE, 1);
        }
    }

    public void add(int days) {
        firstday.add(Calendar.DATE, days);
        init();
    }

    public int getDayNumbers() {
        return dayNumbers;
    }

    // the firstDay should not be changed from outside, so make clone here.
    public Calendar getFirstDay() {
        Calendar f = (Calendar) firstday.clone();
        return f;
    }
    
    public Calendar getLastDay() {
        Calendar lastDay = getFirstDay();
        lastDay.add(Calendar.DATE, dayNumbers - 1);
        return lastDay;
    }

    // return the all-day entries according to the date parameter
    public List<Entry> getAllDayEntries(Calendar date) {
        List<Entry> entryiesByDate = getEntriesByDate(date);
        List<Entry> allDayEntries = new ArrayList<Entry>();
        for (Entry entry : entryiesByDate) {
            if (entry.isAllday()) {
                allDayEntries.add(entry);
            }
        }
        return allDayEntries;
    }

    public List<Entry> getEntriesByDate(Calendar date) {
        List<Entry> dayEntries = new ArrayList<Entry>();
        for (Entry entry : this.entries) {
            if (entry.isDateContained(date)) {
                dayEntries.add(entry);
            }
        }
        return dayEntries;
    }
    
    public DayModel getDayModel(int index) {
        return this.dayModels.get(index);
    }
    
    public void reloadEntries() {
        this.entries = EntryController.LoadEntries();
    }
}
